<?php
	session_start();
	if(!isset($_SESSION["jara_admin"])) {
		header("Location: ../login.php");
		exit;
	}
	if($_SESSION["jara_permissions"][0] == 0) {	
		header("Location: error.php");
		exit;
	}
	require_once("../include/templating_fns.php");
	require_once("../include/db_fns.php");
	jara_page_start("Write Post - Administrator CP");
	if(isset($_REQUEST["write_action"])) {
		try {
			$title = $_POST["title"];
			$author = $_SESSION["jara_admin"];
			$text = $_POST["text"];
			$categoryid = $_POST["categoryid"];
			$time = time();
			if(!get_magic_quotes_gpc()) {
				$title = addslashes($title);
				$text = addslashes($text);
			}
			$query = "insert into jara_posts values('0', '$title', '$author', '$time', '$text', '0', '$categoryid')";
			if(isset($_POST["allowcomments"])) {
				$query = "insert into jara_posts values('0', '$title', '$author', '$time', '$text', '1', '$categoryid')";
			}
			$result = jara_db_query($query);
			if($result == 0) {
				throw new JaraGeneralException("Couldn't add the post $title to the database.");
			}
			else {
				echo "<p>Added post successfully.<br />";
				echo "<a href=\"../index.php\">View latest posts</a></p>";
				jara_page_end();
				exit;
			}
		}
		catch(JaraDatabaseException $ex) {
?>
	<p>
		A database error occured during the process of creating this page.
	</p>
	<p>
		Error type: <?php echo (($ex->getSqlStage() == 1) ? "MySQL connection error" : "MySQL query error"); ?><br />
		Error message: &quot;<?php echo $ex->getSqlMsg(); ?>&quot; [code <?php echo $ex->getSqlCode(); ?>]
	</p>
<?php
			jara_page_end();
		}
		catch(JaraGeneralException $ex) {
?>
	<p>
		A general error occured during the process of creating this page.
	</p>
	<p>
		Error message: &quot;<?php echo $ex->getMessage(); ?>&quot;
	</p>
<?php
			jara_page_end();
		}
		exit;
	}
?>
<form action="write_post.php" method="post">
<p>
<input type="hidden" name="write_action" id="write_action" value="post" />
Post title: <input type="text" id="title" name="title" style="width: 500px" /><br />
Write your post:<br />
<textarea name="text" id="text" cols="60" rows="8"></textarea>
<script language="JavaScript" type="text/javascript" src="scripts/wysiwyg.js"></script>
<script language="JavaScript" type="text/javascript">WYSIWYG.attach('text');</script>
<br /><br />
<input type="checkbox" name="allowcomments" id="allowcomments" checked="checked" /> Allow Comments<br />
Category: <select name="categoryid" id="categoryid"><?php $result = jara_db_query("select * from jara_categories"); for($i = 0; $i < $result->num_rows; $i++) { $row = $result->fetch_assoc(); ?><option value="<?php echo $row["categoryid"]; ?>"><?php echo $row["title"]; ?></option><?php } ?></select><br />
<input type="submit" value="Post!" />
</p>
</form>
<?php
	jara_page_end();
?>